package com.vf.cloud.server.colony;

import java.util.Map;

import com.jfinal.kit.StrKit;
import com.vf.cloud.common.constant.Cache;
import com.vf.cloud.common.domain.Config;
import com.vf.cloud.server.colony.server.NServer;

public class NodeServer {

	public static void main(String[] args) {
		NodeServer.getInstance().run();
	}

	private static volatile NodeServer INSYANCE;

	private NServer server;

	private NodeServer() {
		server = new NServer();
		server.reconnect();
	}

	public static NodeServer getInstance() {
		if (null == INSYANCE) {
			synchronized (NodeServer.class) {
				if (null == INSYANCE) {
					INSYANCE = new NodeServer();
				}
			}
		}
		return INSYANCE;
	}

	public void run() {
		if (server != null) {
			server.run();
		}
	}

	public void restart() {
		if (server != null) {
			server.restart();
		}
	}

	public void stop() {
		if (server != null) {
			server.stop();
		}
	}
	
	public void destroy() {
		if (server != null) {
			server.destroy();
		}
	}

	public int getStatus() {
		if (server != null) {
			return server.getStatus();
		}
		return -1;
	}

	public boolean verify() {
		if (Cache.config == null) {
			return false;
		}
		if (StrKit.isBlank(Cache.config.getMasterIp())) {
			return false;
		}
		if (StrKit.isBlank(Cache.config.getMasterPort())) {
			return false;
		}
		if (StrKit.isBlank(Cache.config.getMasterPwd())) {
			return false;
		}
		return true;
	}

	public void restart(Config config) {
		if (config != null) {
			Cache.config = config;
			stop();
		}
	}

	public void send(Map<String, Object> message) {
		server.send(message);
	}

}
